#include "AnimationInfo.h"
#include "AnimationManager.h"
#include "../../SGD_Wrappers/CSGD_TextureManager.h"
#include "../../SGD_Wrappers/CSGD_EventSystem.h"

CAnimationInfo::CAnimationInfo()
{
	m_cAnimation = nullptr;
	m_fFrame = 0;
	m_fDuration = 0;
	m_bLooping = false;
}

void CAnimationInfo::SetAnimation(std::string sName,bool bLooping)
{
	m_cAnimation = CAnimationManager::GetInstance()->GetAnimation(sName);
	m_fFrame = 0;
	m_fDuration = 0;
	m_bLooping = bLooping;
}

void CAnimationInfo::Update(float fElapsedTime)
{
	if(m_cAnimation!=nullptr)
	{
		m_fDuration -= fElapsedTime;
		if(m_fDuration<=0)
		{
			m_fFrame++;
			if((unsigned int)m_fFrame>=m_cAnimation->m_vFrame.size())
			{
				if(m_bLooping)
					m_fFrame = 0;
				else
					m_fFrame = m_cAnimation->m_vFrame.size() - 1;
			}
			if(m_cAnimation->m_vFrame.size())
			{
				m_fDuration = m_cAnimation->m_vFrame[m_fFrame]->m_fFrameDuration;
				if(m_cAnimation->m_vFrame[m_fFrame]->m_sEventTrigger!="")
					CSGD_EventSystem::GetInstance()->SendEvent(m_cAnimation->m_vFrame[m_fFrame]->m_sEventTrigger,nullptr,nullptr,this);
			}
		}
	}
}

void CAnimationInfo::Draw(float x, float y, float rotation)
{
	if(m_cAnimation!=nullptr)
	{
		if((m_fFrame >= 0) && ((unsigned int)m_fFrame < m_cAnimation->m_vFrame.size()))
		{
			int offImageX = (int)abs(m_cAnimation->m_vFrame[m_fFrame]->m_rSourceRect.left - m_cAnimation->m_vFrame[m_fFrame]->AnchorX); 
			int offImageY = (int)abs(m_cAnimation->m_vFrame[m_fFrame]->m_rSourceRect.top - m_cAnimation->m_vFrame[m_fFrame]->AnchorY)  ; 
			float scale = 0.5f;

			CSGD_TextureManager::GetInstance()->Draw(m_cAnimation->m_vFrame[m_fFrame]->m_nTextureID,
				(int)x-offImageX * (int)scale,(int)y-offImageY * (int)scale,scale,scale,
				&m_cAnimation->m_vFrame[m_fFrame]->m_rSourceRect,
				(float)offImageX,(float)offImageY,
				rotation);
		}
	}
}
